package orm

import (
	"duoke/utils/gconv"
	"duoke/utils/yaml"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/sirupsen/logrus"
	"os"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
)

var Db *xorm.Engine

func Init() {
	config := yaml.GetConfig()
	var err error
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local", config.Mysql.Username, config.Mysql.Password, config.Mysql.Host, gconv.String(config.Mysql.Port), config.Mysql.Name, config.Mysql.Charset)
	Db, err = xorm.NewEngine("mysql", dsn)
	if err != nil {
		logrus.Fatal("数据库引擎创建失败:", err.Error())
		return
	}
	err = Db.Ping()
	if err != nil {
		logrus.Fatal("数据库连接失败:", err.Error())
		return
	}
	logWriter, err := os.Create("log/xorm.log")
	if err != nil {
		logrus.Fatal(err.Error())
		return
	}
	Db.ShowSQL(true) //开启在控制台打印出生成的SQL语句
	Db.Logger().SetLevel(log.LOG_ERR)
	Db.SetLogger(log.NewSimpleLogger(logWriter))
	Db.SetMaxIdleConns(50)
	Db.SetMaxOpenConns(100)
	Db.SetConnMaxLifetime(time.Second * 30)
	// 初始化gf配置
	gdb.SetConfig(gdb.Config{
		"default": gdb.ConfigGroup{
			gdb.ConfigNode{
				Host:    config.Mysql.Host,
				Port:    gconv.String(config.Mysql.Port),
				User:    config.Mysql.Username,
				Pass:    config.Mysql.Password,
				Name:    config.Mysql.Name,
				Charset: config.Mysql.Charset,
				Type:    "mysql",
				Role:    "master",
				Weight:  100,
			},
		},
	})
}
